/* ------------------------------------------------------------------------*
 *
 * ------------------------------------------------------------------------*/

#include "bsp.h"
#include "pincfg.h"
#include "os_obj.h"
#include "mbapp.h"
#include "com_def.h"
#include "bsp_cpu_it.h"
#include "bsp_uart_timer.h"
#include "pincfg.h"

//针对IO模块，超时改为50ms
#define qc_port USART1
#define qc_uart_irqn USART1_IRQn
#define qc_isr QC_USART1_IRQHandler
#define qc_obj mb.qc01
#define qc_cmd_list mb.qc_cmd01

//RS485 Dir-Pin
#define qc_rx_enable()
#define qc_tx_enable()

#include "bsp_qcom_gen.c"
qcom_api_make(USART1, qc_obj);

/*****************************************************************************
* @brief   mb port.
* @param   none
* @return  none
* @ Pass/ Fail criteria: none
*****************************************************************************/
static void qc_port_hal_cfg(void)
{
	intx_alloc();

	nvic_irq_set(qc_uart_irqn, 0x0F, 0);

	intx_disable();

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
    RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, ENABLE);
    RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, DISABLE);

	intx_enable();
}

/*****************************************************************************
* @brief   mb_cb_set
* @param   none
* @return  none
* @ Pass/ Fail criteria: none
*****************************************************************************/
static qc_com_slave_type qc_com_slave = 
{
	qc_reg_set,
	qc_reg_get
};

static qc_mb_slave_type qc_mb_slave =
{
	qc_reg_set,
	qc_reg_get,
	qc_reg_get,
	qc_coil_dat_set,
	qc_coil_dat_get,
	qc_coil_dat_get,
};

static void qc_cb_set(void)
{
	qc_obj_init(&qc_obj, qc_cmd_list, sizeof(qc_cmd_list)/sizeof(qc_cmd_list[0]), 4);
	
	(void) qc_com_slave;
	(void) qc_mb_slave;
	
	qc_obj.slave = &qc_mb_slave;
	qcom_api_link(USART1, qc_obj);
}

static void qc_timer_run(void)
{
	qc_timer_handle(&qc_obj);
}

/*****************************************************************************
* @brief   mb init .
* @param   mbMode
* @param   ulBaudRate
* @param   eParity
* @return  none
* @ Pass/ Fail criteria: none
*****************************************************************************/
void qc01_Init(uu8 qcMode, uint32_t ulBaudRate,mb_parity_type eParity)
{
	// 禁用中断
	nvic_irq_set(qc_uart_irqn, 0x0F, 0);
	uart_timer.uart01 = 0;

	// 中断映射
	cpu_it.uart01 = qc_isr;

	// 初始化
	qc_port_Init(qcMode, ulBaudRate,eParity);

	// 链接定时器任务
	uart_timer.uart01 = qc_timer_run;
	app_timer_task_add(uart01_timer_handle);
}
